package com.shengwei.truck.driver.bean;
import android.os.CountDownTimer;
import android.widget.Button;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.utils.MyLogCat;

/**
 * 短信验证码倒计时
 */
public class TimeCount extends CountDownTimer implements LifecycleObserver {
  private Button button;
  String TAG = "TimeCount";

  /**
   * @param button： 获取验证码按钮
   * @param millisInFuture： 总时长
   * @param countDownInterval：倒计时间隔，如每次减去1秒
   */
  public TimeCount(Button button, long millisInFuture, long countDownInterval) {
    super(millisInFuture, countDownInterval);
    this.button = button;
  }
  
  //计时过程显示
  @Override
  public void onTick(long millisUntilFinished) {
    String time = "(" + millisUntilFinished / 1000 + ")秒";
    int colorDisable = button.getResources().getColor(R.color.describe_color);
    setButtonInfo(time, colorDisable, false);
  }
 
  //计时完毕时触发
  @Override
  public void onFinish() {
    String againGet = button.getResources().getString(R.string.again_get);
    int colorDisable = button.getResources().getColor(R.color.describe_color);
    setButtonInfo(againGet, colorDisable, true);
  }
 
  /**
   * “获取验证码”按钮 点击前后，文本及颜色的变化
   *
   * @param text          按钮显示文本
   * @param colorDisable  按钮禁止点击时的颜色
   * @param isEnable     是否可点击
   */
  private void setButtonInfo(String text, int colorDisable, boolean isEnable) {
    button.setText(text);
    button.setClickable(isEnable);
    if(isEnable){
      button.setBackgroundResource(R.drawable.shape_sms_button);//gxw+
      int textColor = button.getContext().getResources().getColor(R.color.title_color);
      button.setTextColor(textColor);
    }
    else { //不可单击
      int textColor = button.getContext().getResources().getColor(R.color.colorPrimary);
      button.setTextColor(textColor);
    }
  }

  /**
   * 使用Lifecycle感知页面(如Activity)的退出，从而释放定时器等内存资源
   */
  @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
  public void onDestroy() {
    MyLogCat.i(TAG,"ON_DESTROY");
    this.cancel();
  }
}